﻿#include "g711encoder.h"
#include "udprecord.h"
#include <QAudioEncoderSettings>


UDPRecord::UDPRecord(QString ip,quint16 port, QObject *parent)
    : QObject(parent),remoteIp(ip),remotePort(port)
{
//    QAudioFormat format;
    format.setSampleRate(8000);
    format.setChannelCount(1);
    format.setSampleSize(16);
    format.setCodec("audio/pcm");
    format.setByteOrder(QAudioFormat::LittleEndian);
    format.setSampleType(QAudioFormat::SignedInt);

    //If format isn't supported find the nearest supported
    QAudioDeviceInfo info(QAudioDeviceInfo::defaultInputDevice());
    if (!info.isFormatSupported(format)){
        qWarning() << "Default format not supported, trying to use the nearest.";
        format = info.nearestFormat(format);
    }
//    audioInput = new QAudioInput(format,this);

    sendSocket = new QUdpSocket(this);
    sendSocket->connectToHost(remoteIp, remotePort);


    // 连接信号槽以处理音频数据
//    connect(audioInput, &QAudioInput::notify, this, &UDPRecord::handleNotify);

    qDebug()<<"UDPRecord";
}
UDPRecord::~UDPRecord()
{

}

void UDPRecord::processData()
{
    const int fixedBlockSize = 320; // 固定块大小为 320 字节


    if(audioInput->bytesReady()>= fixedBlockSize)
    {
        // 从音频输入设备读取数据
        QByteArray audioData;
        QByteArray encodedData;
        audioData.resize(audioInput->bytesReady());
        recordIODevice->read(audioData.data(), audioData.size());
        qDebug()<<"编码前audioData的大小： "<< audioData.size();
        //将音频数据转换为16位有符号整数数组：
        const int16_t *pcmSamples = reinterpret_cast<const int16_t*>(audioData.constData());
        //计算音频样本的数量：
        int sampleCount = audioData.size() / sizeof(int16_t);
                for (int i = 0; i < sampleCount; ++i) {
                    uint8_t encodedSample = G711Encoder::linear2alaw(pcmSamples[i]);
                    encodedData.append(encodedSample);
                    qDebug() << "PCM:" << pcmSamples[i] << "A-law Encoded:" << encodedSample;
                }
        sendSocket->write(encodedData);
    }
}

void UDPRecord::startAudio()
{

    audioInput = new QAudioInput(format,this);
    //设置音频缓冲区大小
    audioInput->setBufferSize(320);
    //返回用于从系统音频输入传输数据的内部 QIODevice 指针。
    //注意：在停止数据流或启动另一个数据流后，指针将失效。
    recordIODevice = audioInput->start();
    connect(recordIODevice,&QIODevice::readyRead,
            this,&UDPRecord::processData);

    qDebug()<<"startAudio"<<recordIODevice<<audioInput;
}

void UDPRecord::stopAudio()
{
    qDebug()<<"stopRecord1"<<recordIODevice<<audioInput;
    audioInput->stop();
    audioInput->disconnect();

    recordIODevice->disconnect();
    recordIODevice->close();

    delete audioInput;
    delete recordIODevice;
    qDebug()<<"stopRecord2"<<recordIODevice<<audioInput;

    recordIODevice = nullptr;
    audioInput = nullptr;
    qDebug()<<"stopRecord3"<<recordIODevice<<audioInput;

}

void UDPRecord::handleNotify(const QAudioBuffer &buffer)
{


}
